<template>
  <a-row
    justify="center"
    align="middle"
    style="height: 100vh; background-color: #f0f2f5; padding: 0 16px"
  >
    <a-col>
      <a-card style="min-width: 400px">
        <h2 style="text-align: center; margin-bottom: 20px;color: #555">简图-用户注册</h2>
        <a-form layout="vertical" :model="form" :rules="rules" @finish="onSubmit" autocomplete="off" >
          <!-- 用户名 -->
          <a-form-item name="username" required>
            <a-input v-model:value="form.username" placeholder="请输入用户名" />
          </a-form-item>

          <!-- 密码 -->
          <a-form-item name="password" required>
            <a-input-password v-model:value="form.password" placeholder="请输入密码" />
          </a-form-item>

          <!-- 确认密码 -->
          <a-form-item
            name="confirmPassword"
            required
            :rules="[
              { required: true, message: '请再次输入密码', trigger: 'blur' },
              { validator: validateConfirmPassword, trigger: 'blur' },
            ]"
          >
            <a-input-password v-model:value="form.confirmPassword" placeholder="请确认密码" />
          </a-form-item>

          <!-- 注册按钮 -->
          <a-form-item>
            <a-button type="primary" block htmlType="submit">注册</a-button>
          </a-form-item>
        </a-form>

        <!-- 跳转到登录链接 -->
        <div style="text-align: center">
          <a-space>
            <span style="color: #bbb">已经有账号了？</span>
            <a @click="goToLogin">立即登录</a>
          </a-space>
        </div>
      </a-card>
    </a-col>
  </a-row>
</template>

<script setup lang="ts">
import { reactive } from 'vue'
import { message } from 'ant-design-vue'
import { userRegister } from '@/request/api.ts'
import { User, UserAddReq } from '@/proto/user.ts'

// 表单数据类型
interface FormData {
  username: string
  password: string
  confirmPassword: string
}

// 表单数据
const form: FormData = reactive({
  username: '',
  password: '',
  confirmPassword: '',
})

// 表单校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名至少3个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码至少6个字符', trigger: 'blur' },
  ],
}

// 自定义确认密码校验
const validateConfirmPassword = (_: unknown, value: string): Promise<void> => {
  if (value !== form.password) {
    return Promise.reject(new Error('两次输入的密码不一致'))
  }
  return Promise.resolve()
}

// 注册提交事件
const onSubmit = () => {
  userRegister(
    new UserAddReq({
      user: new User({
        account: form.username,
        password: form.password,
        name: form.username,
      }),
    }),
  ).then(() => {
    message.success('注册成功！')
    // 模拟跳转到登录页面
    window.location.href = '/user/login'
  })
}

// 跳转到登录页面
const goToLogin = () => {
  window.location.href = '/user/login' // 根据实际路由修改路径
}
</script>

<style scoped>
/* 自定义样式 */
</style>
